USE ServerMonitor
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[HelpByteUnitSwitch]') AND type in (N'FN', N'IF', N'TF', N'FS', N'FT'))
DROP FUNCTION [dbo].[HelpByteUnitSwitch]
GO
USE ServerMonitor
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE FUNCTION [dbo].[HelpByteUnitSwitch] (@size BIGINT = 0, @unit VARCHAR(2) = 'B')
RETURNS VARCHAR(256)
AS
BEGIN
    DECLARE @targetStr VARCHAR(256)
    DECLARE @norm1 BIGINT, @norm2 BIGINT, @norm3 BIGINT, @norm4 BIGINT
    SET @norm1 = 1024
    SET @norm2 = @norm1 * @norm1
    SET @norm3 = @norm2 * @norm1
    SET @norm4 = @norm3 * @norm1
    SET @targetStr = ''
    SET @unit = UPPER(RTRIM(LTRIM(@unit)))
    IF (@size < 0 OR @unit NOT IN ('B','KB','MB','GB','TB') OR @size IS NULL) RETURN(@targetStr)
    
    SET @size = @size *
                    CASE
                        WHEN (@unit = 'B')  THEN 1
                        WHEN (@unit = 'KB') THEN @norm1
                        WHEN (@unit = 'MB') THEN @norm2
                        WHEN (@unit = 'GB') THEN @norm3
                        WHEN (@unit = 'TB') THEN @norm4                        
                    END
    SET @targetStr = 
                    CASE
                        WHEN (@size < @norm1) THEN CONVERT(VARCHAR(100),@size) + ' B'   
                        WHEN (@size < @norm2) THEN CONVERT(VARCHAR(100),CONVERT(DECIMAL(10,2),(@size / (@norm1 * 1.0)))) + ' KB'      
                        WHEN (@size < @norm3) THEN CONVERT(VARCHAR(100),CONVERT(DECIMAL(10,2),(@size / (@norm2 * 1.0)))) + ' MB'   
                        WHEN (@size < @norm4) THEN CONVERT(VARCHAR(100),CONVERT(DECIMAL(10,2),(@size / (@norm3 * 1.0)))) + ' GB'   
                        ELSE CONVERT(VARCHAR(100),CONVERT(DECIMAL(10,2),(@size / (@norm4 * 1.0)))) + ' TB'
                    END                                   
    RETURN(@targetStr)
END



GO


